/*
 *    Thing Game Library
 *   Copyright (C)2005 - 2010 Eduardo Nunes Pereira (eduardonunesp at gmail dot com)
 *
 *   This program/library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 *   This program/library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 *    You should have received a copy of the GNU Lesser General Public
 * License along with this program/library ; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "logger.hpp"
#include <cstdio>
#include <cstdarg>
#include <iostream>
#include <sstream>
#include <sys/time.h>

Logger *Logger::_instance = NULL;

void Logger::setLogFile(const std::string &file_name)
{
    _log_file.open(file_name.c_str(),std::ios_base::trunc);
    if(!_log_file.is_open()) {
        std::stringstream s;
        s << "Warning: error while open opening ";
        s << file_name;
        s << " for writting.";
        this->error(s.str());
    }
}

void Logger::log(const char *str,...)
{
    char *buf = new char[1024];
    va_list ap;

    va_start(ap, str);
    vsprintf(buf, str,ap);
    va_end(ap);

    /* Get the current system time */
    timeval tv; 
    gettimeofday(&tv, NULL);

    /* Print the log entry */
    std::stringstream time_str;
    time_str << "[" 
        << ((((tv.tv_sec / 60) / 60) % 24 < 10) ? "0" : "") 
        << (int)(((tv.tv_sec / 60) / 60) % 24) 
        << ":" 
        << (((tv.tv_sec / 60) % 60 < 10) ? "0" : "") 
        << (int)((tv.tv_sec / 60) % 60) 
        << ":" 
        << ((tv.tv_sec % 60 < 10) ? "0" : "") 
        << (int)(tv.tv_sec % 60) 
        << "." 
        << (((tv.tv_usec / 10000) % 100) < 10 ? "0" : "") 
        << (int)((tv.tv_usec / 10000) % 100)
        << "] ";

    if(_log_file.is_open()) {
        _log_file << time_str.str() << buf << "\n";
    }

    delete[] buf;
}

void Logger::error(const std::string &error_text)
{
    std::cerr << "Error: " << error_text << std::endl;
}
